<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="商户号" prop="merId" v-if="isAdmin">
        <el-input
          v-model="queryParams.merId"
          placeholder="请输入商户号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户名称" prop="merName" v-if="isAdmin">
        <el-input
          v-model="queryParams.merName"
          placeholder="请输入商户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号码" prop="userCardid">
        <el-input
          v-model="queryParams.userCardid"
          placeholder="请输入证件号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="userMobile">
        <el-input
          v-model="queryParams.userMobile"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
        >
          <el-link style="color:white;font-size: 12px;" icon="el-icon-download" :underline="false"
                   href="http://storage.guzift.com/template/%E7%94%A8%E6%88%B7%E7%AD%BE%E7%BA%A6%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E6%A0%BC%E5%BC%8F%E6%A8%A1%E6%9D%BF.xlsx">
            下载导入模板
          </el-link>
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-upload
          class="upload-demo"
          :action="userUploadUrl"
          :headers="myHeaders"
          :show-file-list="false"
          :on-success="handleUserImport"
          :multiple="false">
          <el-button
            type="info"
            icon="el-icon-upload"
            size="mini"
            v-hasPermi="['user:user:import']"
          >导入
          </el-button>
        </el-upload>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['user:user:export']"
        >导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-upload
          class="upload-demo"
          :action="imageBatchUploadUrl"
          :headers="myHeaders"
          :show-file-list="false"
          :on-success="handleImageBatchUpload"
          :multiple="false">
          <el-tooltip placement="top">
            <div slot="content">1.上传文件名必须为zip格式<br/>2.文件大小不能超过50M<br/>3.压缩文件中的证件图片格式为(证件正面:411321199910252345_1.jpg 或
              证件反面:411321199910252345_2.jpg)
            </div>
            <el-button
              type="success"
              icon="el-icon-upload"
              size="mini"
              v-hasPermi="['user:user:imageBatchUpload']"
            >证件照片批量上传
            </el-button>
          </el-tooltip>

        </el-upload>
      </el-col>



    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商户号" align="center" prop="merId" v-if="isAdmin"/>
      <el-table-column label="商户名称" align="center" prop="merName" v-if="isAdmin"/>
      <el-table-column label="注册渠道" align="center" prop="regChannel"
                       :formatter="regChannelFormat"/>
      <el-table-column label="用户编号" align="center" prop="id"/>
      <el-table-column label="姓名" align="center" prop="userName"/>
      <el-table-column label="证件类型" align="center" prop="cardidType"
                       :formatter="cardidTypeFormat"/>
      <el-table-column label="证件号码" width="200" align="center" prop="userCardid"/>
      <el-table-column label="手机号" width="140" align="center" prop="userMobile"/>
      <el-table-column label="银行卡号" width="180" align="center" prop="bankCardno"/>
      <el-table-column label="邮箱" width="160" align="center" prop="userEmail"/>
      <el-table-column label="注册状态" align="center" prop="regStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.regStatus === '0'"><el-tag type="info" effect="dark" size="mini">未注册</el-tag></span>
          <span v-if="scope.row.regStatus === '1'"><el-tag type="success" effect="dark" size="mini">成功</el-tag></span>
          <span v-if="scope.row.regStatus === '2'"><el-tag type="warning" effect="dark" size="mini">注销</el-tag></span>
          <span v-if="scope.row.regStatus === '3'"><el-tag type="danger" effect="dark" size="mini">失败</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="注册日期" align="center" prop="regDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.regDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实名认证状态" align="center" prop="certStatus"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.certStatus === '1'"><el-tag type="info" effect="dark" size="mini">未实名</el-tag></span>
          <span v-if="scope.row.certStatus === '2'"><el-tag type="success" effect="dark" size="mini">已实名</el-tag></span>
          <span v-if="scope.row.certStatus === '3'"><el-tag type="warning" effect="dark" size="mini">处理中</el-tag></span>
          <span v-if="scope.row.certStatus === '4'"><el-tag type="danger" effect="dark" size="mini">实名失败</el-tag></span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-coordinate"
            @click="handleUpdateCertStatus(scope.row,2)"
            v-hasPermi="['user:user:certStatus']"
            v-if="scope.row.certStatus !== '2'"
          >实名认证
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewUpdate(scope.row,'view')"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleViewUpdate(scope.row,'edit')"
            v-hasPermi="['user:user:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['user:user:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户注册对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" @close="clearPic">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">

        <el-form-item label="商户号" prop="merId" v-if="isAdmin">
          <el-input  v-model="form.merId"  placeholder="请输入商户号"  disabled/>
        </el-form-item>

        <el-form-item label="商户名称" prop="merName" v-if="isAdmin">
          <el-input v-model="form.merName" placeholder="请输入商户名称"  disabled/>
        </el-form-item>

        <el-form-item label="注册渠道">
          <el-select v-model="form.regChannel" placeholder="请选择注册渠道" disabled>
            <el-option
              v-for="dict in regChannelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select v-model="form.cardidType" placeholder="请选择证件类型">
            <el-option
              v-for="dict in cardidTypeOptions"
              :key="dict.dictValue  + ''"
              :label="dict.dictLabel  + ''"
              :value="dict.dictValue + ''"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="userCardid">
          <el-input v-model="form.userCardid" placeholder="请输入证件号码"/>
        </el-form-item>
        <el-form-item label="手机号" prop="userMobile">
          <el-input v-model="form.userMobile" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankCardno">
          <el-input v-model="form.bankCardno" placeholder="请输入银行卡号"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="form.userEmail" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="注册状态">
          <el-select v-model="form.regStatus" placeholder="请选择注册状态">
            <el-option
              v-for="dict in regStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册日期" prop="regDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.regDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择注册日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实名认证状态">
          <el-select v-model="form.certStatus" placeholder="请选择实名认证状态" disabled>
            <el-option
              v-for="dict in certStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <div style="margin-top:50px">
              <el-form-item label="身份证正面地址" prop="picFrontUrl">
                <el-input type="hidden" v-model="form.picFrontUrl" placeholder="请输入身份证正面地址"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="18">
            <el-upload
              :class="{hide:frontHide}"
              ref="imageFrontUpload"
              :on-preview="handleFrontUploadPreview"
              :headers="myHeaders"
              :action="imageUploadUrl"
              :on-success="handleFrontUpload"
              :on-remove="handleFrontRemove"
              :file-list="frontList"
              :accept="'image/*'"
              v-hasPermi="['user:user:imageUpload']"
              :limit=1
              :multiple="false"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-col>
        </el-row>
        <div style="margin-top: 20px;"></div>
        <el-row :gutter="20">
          <el-col :span="6">
            <div style="margin-top:50px">
              <el-form-item label="身份证反面面地址" prop="picBackUrl">
                <el-input type="hidden" v-model="form.picBackUrl" placeholder="请输入身份证反面面地址"/>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="18">
            <el-upload
              :class="{hide:backHide}"
              ref="imageBackUpload"
              :on-preview="handleBackUploadPreview"
              :headers="myHeaders"
              :action="imageUploadUrl"
              :on-success="handleBackUpload"
              :on-remove="handleBackRemove"
              :file-list="backList"
              :accept="'image/*'"
              v-hasPermi="['user:user:imageUpload']"
              :limit=1
              :multiple="false"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-col>
        </el-row>

        <div style="margin-top: 20px;"></div>

        <el-form-item label="临时税务登记编号" prop="taxRegId">
          <el-input v-model="form.taxRegId" placeholder="请输入临时税务登记编号"/>
        </el-form-item>
        <el-form-item label="临时税务登记日期" prop="taxRegDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.taxRegDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择临时税务登记日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title !== '查看用户注册'">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="picFrontDialogVisible">
      <img width="100%" :src="picFrontPath" alt="">
    </el-dialog>
    <el-dialog :visible.sync="picBackDialogVisible">
      <img width="100%" :src="picBackPath" alt="">
    </el-dialog>

  </div>
</template>

<script>
  import {listUser, getUser, delUser, addUser, updateUser, exportUser} from "@/api/user/user";
  import {getInfo} from "@/api/login";
  import {getToken} from '@/utils/auth';
  import {updateCertStatus} from "../../../api/user/user";

  export default {
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        loginMerId:"",
        isAdmin: true,
        // 用户注册表格数据
        userList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        userUploadUrl: process.env.VUE_APP_BASE_API + '/user/user/import',
        imageBatchUploadUrl: process.env.VUE_APP_BASE_API + '/user/user/imageBatchUpload',
        imageUploadUrl: process.env.VUE_APP_BASE_API + '/user/user/imageUpload',
        picFrontDialogVisible: false,
        picBackDialogVisible: false,
        frontHide: false,
        backHide: false,
        picFrontPath: "",
        picBackPath: "",
        frontList: [],
        backList: [],
        myHeaders: {Authorization: 'Bearer ' + getToken()},
        // 注册渠道字典
        regChannelOptions: [],
        // 证件类型字典
        cardidTypeOptions: [],
        // 注册状态字典
        regStatusOptions: [],
        // 实名认证状态字典
        certStatusOptions: [],
        // 状态字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          merId: undefined,
          merName: undefined,
          userName: undefined,
          userCardid: undefined,
          userMobile: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          merId: [
            {required: true, message: "商户号不能为空", trigger: "blur"}
          ], merName: [
            {required: true, message: "商户名称不能为空", trigger: "blur"}
          ], regChannel: [
            {required: true, message: "注册渠道不能为空", trigger: "blur"}
          ], userName: [
            {required: true, message: "姓名不能为空", trigger: "blur"}
          ], userCardid: [
            {required: true, message: "证件号码不能为空", trigger: "blur"}
          ], cardidType: [
            {required: true, message: "证件类型不能为空", trigger: "blur"}
          ], userMobile: [
            {required: true, message: "手机号不能为空", trigger: "blur"},
            {pattern: /(\+\d+)?1[345789]\d{9}$/, message: '手机号码格式不正确'}
          ], bankCardno: [
            {required: true, message: "银行卡号不能为空", trigger: "blur"},
            {pattern: /^([1-9]{1})(\d{11}|\d{14}|\d{15}|\d{16}|\d{17}|\d{18}|\d{19})$/, message: '银行卡号格式不正确'}
          ],userEmail: [
              {pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确'}
            ], regStatus: [
            {required: true, message: "注册状态不能为空", trigger: "blur"}
          ], regDate: [
            {required: true, message: "注册日期不能为空", trigger: "blur"}
          ],
        }
      };
    },
    created() {
      getInfo().then(response => {
        this.loginMerId = response.user.merId;
        this.isAdmin = response.user.admin;
      });
      this.getList();
      this.getDicts("reg_channel").then(response => {
        this.regChannelOptions = response.data;
      });
      this.getDicts("cardid_type").then(response => {
        this.cardidTypeOptions = response.data;
      });
      this.getDicts("reg_status").then(response => {
        this.regStatusOptions = response.data;
      });
      this.getDicts("cert_status").then(response => {
        this.certStatusOptions = response.data;
      });
      this.getDicts("status").then(response => {
        this.statusOptions = response.data;
      });
    },
    methods: {
      /** 查询用户注册列表 */
      getList() {
        this.loading = true;
        listUser(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 注册渠道字典翻译
      regChannelFormat(row, column) {
        return this.selectDictLabel(this.regChannelOptions, row.regChannel);
      },
      // 证件类型字典翻译
      cardidTypeFormat(row, column) {
        return this.selectDictLabel(this.cardidTypeOptions, row.cardidType);
      },
      // 注册状态字典翻译
      regStatusFormat(row, column) {
        return this.selectDictLabel(this.regStatusOptions, row.regStatus);
      },
      // 实名认证状态字典翻译
      certStatusFormat(row, column) {
        return this.selectDictLabel(this.certStatusOptions, row.certStatus);
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          merId: undefined,
          merName: undefined,
          regChannel: undefined,
          userName: undefined,
          userCardid: undefined,
          cardidType: undefined,
          userMobile: undefined,
          bankCardno: undefined,
          userEmail: undefined,
          regStatus: undefined,
          regDate: undefined,
          certStatus: undefined,
          picFrontUrl: undefined,
          picBackUrl: undefined,
          taxRegId: undefined,
          taxRegDate: undefined,
          corpCode: undefined,
          corpName: undefined,
          createBy: undefined,
          createDate: undefined,
          reqIp: undefined,
          status: "0",
          updateBy: undefined,
          updateDate: undefined,
          remarks: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加用户注册";
      },
      /** 修改按钮操作 */
      handleViewUpdate(row, type) {
        this.reset();
        const id = row.id || this.ids;
        if (row.picFrontUrl !== '' && row.picFrontUrl != null) {
          this.frontList.push({url: row.picFrontUrl});
          this.frontHide = true;
        }
        if (row.picBackUrl !== '' && row.picBackUrl != null) {
          this.backList.push({url: row.picBackUrl});
          this.backHide = true;
        }
        getUser(id).then(response => {
          this.form = response.data;
          this.open = true;
          if ('edit' === type) {
            this.title = "修改用户注册";
          }
          if ('view' === type) {
            this.title = "查看用户注册";
          }
        });
      },
      handleUpdateCertStatus(row, status){

        this.$confirm('是否确认实名认证?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          updateCertStatus(row.id,status).then(response =>{
            if(2 === response.data){
              this.msgSuccess("认证成功");
            }else{
              this.msgError("认证失败,请核验用户信息");
            }
            this.getList();
          });
        }).catch(function () {
          this.msgError("认证失败");
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateUser(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              addUser(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return delUser(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function () {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出用户注册数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return exportUser(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function () {
        });
      },
      handleUserImport(response) {
        if (response.msg !== 'success') {
          this.download(response.msg);
          this.msgError("导入错误文件已生成, 请修改格式不正确数据!");
        } else {
          this.msgSuccess("导入成功!");
        }
        this.getList();
      },
      /** 处理图片批量上传*/
      handleImageBatchUpload(res) {
        if (res.code === 200) {
          this.msgSuccess("上传成功!");
        } else {
          this.msgError(res.msg);
        }
      },
      /** 处理证件正面预览*/
      handleFrontUploadPreview(file) {
        this.picFrontDialogVisible = true;
        this.picFrontPath = file.url;
      },
      /** 处理证件反面预览*/
      handleBackUploadPreview(file) {
        this.picBackDialogVisible = true;
        this.picBackPath = file.url;
      },
      /** 处理证件正面上传*/
      handleFrontUpload(res) {
        if (res.code === 200) {
          this.frontHide = true;
          this.form.picFrontUrl = res.msg;
          this.msgSuccess("上传成功!");
        } else {
          this.$refs.imageFrontUpload.clearFiles()
          this.msgError(res.msg);
        }
      },
      /** 处理证件反面上传*/
      handleBackUpload(res) {
        if (res.code === 200) {
          this.backHide = true;
          this.form.picBackUrl = res.msg;
          this.msgSuccess("上传成功!");
        } else {
          this.$refs.imageBackUpload.clearFiles()
          this.msgError(res.msg);
        }
      },
      /** 处理证件正面删除*/
      handleFrontRemove(file, fileList) {
        this.frontHide = fileList.length >= 1;
        this.form.picFrontUrl = '';
      },
      /** 处理证件反面删除*/
      handleBackRemove(file, fileList) {
        this.backHide = fileList.length >= 1;
        this.form.picBackUrl = '';
      },
      /** 清空证件,防止多次点击修改,重复显示问题*/
      clearPic() {
        this.frontList = [];
        this.backList = [];
        this.frontHide = false;
        this.backHide = false;
      }
    }
  };
</script>
<style>
  .hide .el-upload--picture-card {
    display: none !important; /* 上传按钮隐藏 */
  }

  .el-upload {
    display: inline-block;
  }
</style>
